package com.idea.relax.sensitive.factory;


import com.idea.relax.sensitive.processor.ISensitiveProcessor;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author: 沉香
 * @date: 2023/7/11
 * @description:
 */
public class SensitiveFactory implements ISensitiveFactory {

	private final static Map<String, Map<Class<?>, ISensitiveProcessor<Object>>> ALGORITHM_POOL = new HashMap<>();

	/**
	 * 获取脱敏算法类
	 * @param name
	 * @param clazz
	 * @return
	 */
	@Override
	public ISensitiveProcessor<Object> get(String name, Class<?> clazz) {
		return Optional.ofNullable(ALGORITHM_POOL.get(name)).map(map -> map.get(clazz)).orElse(null);
	}

	/**
	 * 新增脱敏算法
	 * @param processors
	 */
	@SafeVarargs
	@Override
	public final void add(ISensitiveProcessor<Object>... processors) {
		for (ISensitiveProcessor<Object> processor : processors) {
			if (ALGORITHM_POOL.get(processor.name()) == null) {
				Map<Class<?>, ISensitiveProcessor<Object>> map = new HashMap<>(2);
				map.put(processor.getTargetType(), processor);
				ALGORITHM_POOL.put(processor.name(), map);
			} else {
				ALGORITHM_POOL.get(processor.name()).put(processor.getTargetType(), processor);
			}
		}
	}

}
